﻿using System;
using DhbInterpolation;
using EmbeddedSharp.Core;

namespace EmbeddedSharp.Scripting.Algebra
{
    public class InterpolatedFunction : IUnaryParameterFunction
    {
        private readonly BulirschStoerInterpolator func;

        public InterpolatedFunction(BulirschStoerInterpolator func)
        {
            this.func = func;
        }

        #region IUnaryParameterFunction Members

        public double Eval(double x)
        {
            return func.Value(x);
        }

        #endregion
    }

    public class InterpolateNode : ContextFuncNode
    {
        public InterpolateNode()
            : base("interpolate")
        {
        }

        public override object Evaluate()
        {
            int length = Parameters.Count;
            if (Parameters.Count < 0)
            {
                throw new ArgumentException(
                    "usage: interpolate(x, [[x1,y1],[x2,y],...])");
            }

            var points =
                Parameters[length - 2].Evaluate() as ListObject;
            double to = Convert.ToDouble(
                Parameters[length - 1].Evaluate());

            var ps = new PointSeries();
            foreach (object obj in points)
            {
                var lo = obj as ListObject;

                double x = Convert.ToDouble(lo[0]);
                double y = Convert.ToDouble(lo[1]);
                ps.AddPoint(x, y);
            }

            var i = new BulirschStoerInterpolator(
                ps);

            //InterpolatedFunction f = new InterpolatedFunction(i);
            //return f;

            return i.Value(to);
        }
    }
}